import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import chinaJson from '@noahsun/echarts-map-json/china.json';
import { Button, Space, Typography, Tooltip } from 'antd';
import { ZoomInOutlined, ZoomOutOutlined, ReloadOutlined, GlobalOutlined } from '@ant-design/icons';
import type { ChinaMapData } from '@/services/dashboard';

const { Text } = Typography;

interface ChinaMapProps {
  data: ChinaMapData;
  height?: number;
  onProvinceClick?: (province: string) => void;
  onCityClick?: (province: string, city: string) => void;
}

const ChinaMap: React.FC<ChinaMapProps> = ({ 
  data, 
  height = 300, 
  onProvinceClick, 
  onCityClick 
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [currentLevel, setCurrentLevel] = useState<'province' | 'city'>(
    data.level === 'detail' ? 'city' : data.level
  );

  // 初始化地图
  useEffect(() => {
    if (!chartRef.current) return;

    // 注册中国地图
    echarts.registerMap('china', chinaJson as any);

    // 创建图表实例
    chartInstance.current = echarts.init(chartRef.current);

    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  // 更新地图数据
  useEffect(() => {
    if (!chartInstance.current || !data.mapData.length) return;

    const maxValue = Math.max(...data.mapData.map(item => item.value));
    const minValue = Math.min(...data.mapData.map(item => item.value));

    // 准备地图数据
    const mapData = data.mapData.map(item => ({
      name: data.level === 'province' ? item.province : item.name,
      value: item.value,
      itemStyle: {
        color: getColorByValue(item.value, minValue, maxValue)
      },
      // 存储额外信息用于tooltip
      rawData: item
    }));

    const option: echarts.EChartsOption = {
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          const item = params.data?.rawData || {};
          if (data.level === 'province') {
            return `
              <div style="padding: 8px;">
                <div style="font-weight: bold; margin-bottom: 4px;">${item.province}</div>
                <div>用户数: <span style="color: #1890ff;">${item.unique_users}</span></div>
                <div>访问数: <span style="color: #52c41a;">${item.visits}</span></div>
                <div>IP数: <span style="color: #fa8c16;">${item.unique_ips}</span></div>
                <div>城市数: <span style="color: #722ed1;">${item.city_count}</span></div>
                <div>转化率: <span style="color: #eb2f96;">${item.user_conversion_rate}%</span></div>
              </div>
            `;
          } else {
            return `
              <div style="padding: 8px;">
                <div style="font-weight: bold; margin-bottom: 4px;">${item.province} - ${item.city}</div>
                <div>用户数: <span style="color: #1890ff;">${item.value}</span></div>
                <div>访问数: <span style="color: #52c41a;">${item.visits}</span></div>
              </div>
            `;
          }
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#ccc',
        borderWidth: 1,
        textStyle: {
          fontSize: 12,
          color: '#333'
        }
      },
      visualMap: {
        min: minValue,
        max: maxValue,
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        realtime: false,
        calculable: true,
        inRange: {
          color: ['#e6f3ff', '#bae7ff', '#91d5ff', '#69c0ff', '#40a9ff', '#1890ff', '#096dd9', '#0050b3']
        },
        textStyle: {
          fontSize: 10,
          color: '#666'
        },
        itemWidth: 12,
        itemHeight: 80,
        formatter: (value: any) => {
          return formatNumber(Number(value) || 0);
        }
      },
      geo: {
        map: 'china',
        roam: true, // 允许缩放和平移
        scaleLimit: {
          min: 0.8,
          max: 3
        },
        zoom: 1.1,
        center: [104.0, 37.5], // 中国中心坐标
        itemStyle: {
          borderColor: '#404040',
          borderWidth: 0.5,
          areaColor: '#f5f5f5'
        },
        emphasis: {
          itemStyle: {
            areaColor: '#ffd700',
            borderWidth: 1
          }
        },
        regions: data.mapData.map(item => ({
          name: data.level === 'province' ? item.province : item.name,
          itemStyle: {
            areaColor: getColorByValue(item.value, minValue, maxValue),
            borderColor: '#404040',
            borderWidth: 0.5
          }
        }))
      },
      series: [
        {
          name: data.level === 'province' ? '省份数据' : '城市数据',
          type: 'map',
          map: 'china',
          geoIndex: 0,
          data: mapData,
          roam: true,
          zoom: 1.1,
          center: [104.0, 37.5],
          emphasis: {
            itemStyle: {
              areaColor: '#ffd700'
            }
          }
        }
      ]
    };

    chartInstance.current.setOption(option, true);

    // 添加点击事件
    chartInstance.current.off('click');
    chartInstance.current.on('click', (params: any) => {
      if (params.componentType === 'series' && params.seriesType === 'map') {
        const item = params.data?.rawData || {};
        if (data.level === 'province' && onProvinceClick) {
          onProvinceClick(item.province);
        } else if (data.level === 'city' && onCityClick) {
          onCityClick(item.province, item.city);
        }
      }
    });

  }, [data, currentLevel, onProvinceClick, onCityClick]);

  // 响应式处理
  useEffect(() => {
    const handleResize = () => {
      if (chartInstance.current) {
        chartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 颜色计算函数
  const getColorByValue = (value: number, min: number, max: number): string => {
    if (max === min) return '#91d5ff';
    
    const intensity = (value - min) / (max - min);
    const colors = [
      '#e6f3ff', '#bae7ff', '#91d5ff', '#69c0ff', 
      '#40a9ff', '#1890ff', '#096dd9', '#0050b3'
    ];
    
    const index = Math.floor(intensity * (colors.length - 1));
    return colors[Math.min(index, colors.length - 1)];
  };

  // 数字格式化
  const formatNumber = (num: number): string => {
    if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
    return num.toString();
  };

  // 地图控制函数
  const handleZoomIn = () => {
    if (chartInstance.current) {
      chartInstance.current.dispatchAction({
        type: 'geoZoom',
        zoom: 1.2
      });
    }
  };

  const handleZoomOut = () => {
    if (chartInstance.current) {
      chartInstance.current.dispatchAction({
        type: 'geoZoom',
        zoom: 0.8
      });
    }
  };

  const handleReset = () => {
    if (chartInstance.current) {
      chartInstance.current.dispatchAction({
        type: 'geoRestore'
      });
    }
  };

  return (
    <div className="china-map-container">
      {/* 地图标题和控制按钮 */}
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center space-x-2">
          <GlobalOutlined className="text-blue-500" />
          <Text strong style={{ fontSize: '14px' }}>
            {data.level === 'province' ? '全国省份分布' : '全国城市分布'}
          </Text>
        </div>
        
        <Space size="small">
          <Tooltip title="放大">
            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
          </Tooltip>
          <Tooltip title="缩小">
            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
          </Tooltip>
          <Tooltip title="重置">
            <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
          </Tooltip>
        </Space>
      </div>

      {/* 地图容器 */}
      <div 
        ref={chartRef} 
        style={{ 
          width: '100%', 
          height: `${height}px`,
          backgroundColor: '#fafafa',
          borderRadius: '4px',
          border: '1px solid #e8e8e8'
        }} 
      />

      {/* 统计信息 */}
      <div className="mt-2 text-center">
        <Space split={<span className="text-gray-300">|</span>} size="small">
          <Text type="secondary" style={{ fontSize: '11px' }}>
            覆盖 {data.summary.total_provinces || data.summary.total_cities || 0} 个{data.level === 'province' ? '省份' : '城市'}
          </Text>
          <Text type="secondary" style={{ fontSize: '11px' }}>
            总用户 {formatNumber(data.summary.total_users)}
          </Text>
          <Text type="secondary" style={{ fontSize: '11px' }}>
            总访问 {formatNumber(data.summary.total_visits)}
          </Text>
          <Text type="secondary" style={{ fontSize: '11px' }}>
            最活跃 {data.summary.most_active_province || data.summary.most_active_city || '--'}
          </Text>
        </Space>
      </div>
    </div>
  );
};

export default ChinaMap; 